﻿using HighPerformanceLog.V2;
using System;
using System.IO;
using System.Net.Http;
using System.Threading;
using System.Windows.Forms;

namespace ProcessBarDemo.UpdateFramework
{
    public static class SegmentDownloader
    {
        private static readonly HttpClient client = new HttpClient();

        public static void Download(string url, long from, long to, string filePath)
        {
            const int maxRetries = 3;
            int attempt = 0;


            while (attempt < maxRetries)
            {
                try
                {
                    attempt++;
                    HWLogger.DebugLog($"开始下载 [{filePath}], range={from}-{to}, 尝试 {attempt}");

                    using (var request = new HttpRequestMessage(HttpMethod.Get, url))
                    {
                        request.Headers.Range = new System.Net.Http.Headers.RangeHeaderValue(from, to);

                        using (var response = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead).GetAwaiter().GetResult())
                        {
                            response.EnsureSuccessStatusCode();

                            var netStream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
                            using (netStream)
                            using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                            {
                                byte[] buffer = new byte[40960];
                                int read;
                                long totalRead = 0;

                                while ((read = netStream.Read(buffer, 0, buffer.Length)) > 0)
                                {
                                    fileStream.Write(buffer, 0, read);
                                    ProgressReporter.Report(read);
                                    totalRead += read;
                                }
                                HWLogger.DebugLog($"下载完成 [{filePath}] 共 {totalRead} 字节");
                            }
                        }
                    }

                    return;
                }
                catch (Exception ex)
                {
                    HWLogger.WarningLog($"下载失败 [{filePath}], 尝试 {attempt}, 错误: {ex.Message}");

                    if (attempt >= maxRetries)
                    {
                        MessageBox.Show($"多次尝试后仍下载失败: {filePath}\n错误信息: {ex.Message}", "下载失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return; // 防止 throw 导致程序整体崩溃
                    }

                    Thread.Sleep(100);
                }
            }
        }
    }
}
